package club.jdiy.core.job.entity;

import club.jdiy.core.base.domain.JpaEntity;
import club.jdiy.core.convert.Converter;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * JDiy定时任务执行日志
 *
 * @author ziquee(子秋) QQ号:39886616 主页: http://www.jdiy.club
 * @version 20210622
 */
@NoArgsConstructor
@Data
@Entity
@Table(name = "jdiy_job_log")
public class JDiyJobLog implements JpaEntity<String> {

    @Id
    @Column(length = 64)
    private String id;//scheduledFireTime(yyyyMMddHHmmss) + "_" + jobId

    @Column(columnDefinition = "varchar(64) not null comment '任务名称（a-z0-9）'")
    private String jobName;
    @Column(columnDefinition = "varchar(64) not null comment '任务分组'")
    private String jobGroup;
    @Column(columnDefinition = "text comment '任务执行代码'")
    private String jobExecute;

    @Column(columnDefinition = "int default 0 not null comment '0:完成  1:执行中  2:执行失败'")
    private Integer state;
    @Column(columnDefinition = "text comment '任务执行失败的错误信息'")
    private String errMessage;

    @Column(columnDefinition = "datetime not null comment '任务触发器应当执行的时间点(为空表示手动执行)'")
    private LocalDateTime scheduledFireTime;
    @Column(columnDefinition = "datetime not null comment '任务开始时间(如果scheduledFireTime!=null && startTime!=scheduledFireTime,则有可能是超时后补执行)'")
    private LocalDateTime startTime;
    @Column(columnDefinition = "datetime comment '任务结束时间'")
    private LocalDateTime endTime;

    public static JDiyJobLog jobStartLog(JDiyJob job, Date scheduledFireTime) {
        JDiyJobLog jjl = new JDiyJobLog();
        jjl.jobName = job.getJobName();
        jjl.jobGroup = job.getJobGroup();
        jjl.jobExecute = job.getJobExecute();
        jjl.state = 1;
        if (scheduledFireTime != null) jjl.scheduledFireTime = Converter.of(scheduledFireTime).getLocalDateTime();
        jjl.startTime = LocalDateTime.now();
        jjl.setId(
                createLogId(
                        jjl.getScheduledFireTime() == null ? jjl.getStartTime() : jjl.getScheduledFireTime()
                        , job.getId()
                )
        );
        return jjl;
    }

    public static String createLogId(LocalDateTime dt, Long jobId) {
        return dt.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + "_" + jobId;
    }
}